package com.hanshg.cherry.controller.kaptcha;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hanshg.cherry.base.core.Constants;
import com.hanshg.cherry.util.redis.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @ClassName KaptchaController
 * @Description 生成验证码
 * @Author 柠檬水
 * @Date 2020/4/11 15:39
 * @Version 1.0
 **/
@Controller
@Slf4j
@RequestMapping("kaptcha")
@Api(tags = "验证码控制器")
public class KaptchaController {

    private final RedisUtil redisUtil;

    private final DefaultKaptcha defaultKaptcha;

    public KaptchaController(DefaultKaptcha defaultKaptcha, RedisUtil redisUtil) {
        this.defaultKaptcha = defaultKaptcha;
        this.redisUtil = redisUtil;
    }

    /**
     * gif代码
     * 获取验证码
     *
     * @param response 响应
     * @param request  请求
     * @throws IOException ioexception
     */
    @GetMapping("/getVerifyCode")
    @ApiOperation("生成图形验证码")
    @ApiOperationSupport(author = "柠檬水 cherryok@126.com")
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        byte[] verByte;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            redisUtil.set(Constants.LOGIN_VERIFY_SESSION,createText, Constants.SMS_USER_EXPIRE);
            log.info("验证码生成,已存入Redis,过期时间2分钟：" + createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        verByte = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(verByte);
        outputStream.flush();
        outputStream.close();
        log.info("生成验证码结束");
    }
}
